package com.tanhua.dubbo.api.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.db.*;
import com.tanhua.domain.mongo.SoulReport;
import com.tanhua.domain.mongo.SoundTime;
import com.tanhua.domain.mongo.UserSound;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.SoulTestApi;
import com.tanhua.dubbo.mapper.*;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class SoulTestApiImpl implements SoulTestApi {
    @Autowired
    private SoulTestMapper soulTestMapper;
    @Autowired
    private SoulQuestionMapper questionMapper;
    @Autowired
    private QuestionOptionMapper questionOptionMapper;
    @Autowired
    private SoulConclusionMapper conclusionMapper;
    @Autowired
    private  MongoTemplate mongoTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;
    public List<SoulTestVo> getTestList(Long userId) {
        List<SoulTest> soulTests = soulTestMapper.selectList(null);
        List<SoulTestVo> listSoulTest=new ArrayList<>();
        //查询所有问题主题
        for (SoulTest soulTest : soulTests) {
            //创建一个TestSoulVo
            SoulTestVo testSoulVo=new SoulTestVo();
            //获取id查询question问题
            Integer id = soulTest.getId();
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("sid",id);
            List<SoulQuestion> list = questionMapper.selectList(wrapper);
            //先创建SoulQuestionVo list封装
            List<SoulQuestionVo> questionVos=new ArrayList<>();

            //遍历封装并查询option封装
            for (SoulQuestion soulQuestion : list) {

                //封装question list
                SoulQuestionVo questionVo=new SoulQuestionVo();
                questionVo.setQuestion(soulQuestion.getQuestion());
                questionVo.setId(soulQuestion.getId().toString());

                //查询option
                Integer optionQid = soulQuestion.getId();
                QueryWrapper wrapper1=new QueryWrapper();
                wrapper1.eq("qid",optionQid);
                List<QuestionOption> optionsList = questionOptionMapper.selectList(wrapper1);
                List<QuestionOptionVo> questionOptionVos=new ArrayList<>();
                //遍历封装optionvo
                for (QuestionOption questionOption : optionsList) {
                    if(questionOption.getIsdefault()==0) {
                        QuestionOptionVo optionVo = new QuestionOptionVo();
                        optionVo.setOption(questionOption.getOptions());
                        optionVo.setId(questionOption.getId().toString());
                        questionOptionVos.add(optionVo);
                    }
                }
                //封装TestSoulVo,封装id，封装questionvo，封装optionvo
                questionVo.setOptions(questionOptionVos);
                questionVos.add(questionVo);
            }

            BeanUtils.copyProperties(soulTest,testSoulVo);
            testSoulVo.setId(soulTest.getId().toString());
            testSoulVo.setQuestions(questionVos);
            //判断该userId是否存在报告
            Query query=new Query(Criteria.where("userId").is(userId).and("level").is(soulTest.getLevel()));
            SoulReport one = mongoTemplate.findOne(query, SoulReport.class);
            testSoulVo.setReportId(null);
            testSoulVo.setIsLock(1);
            if(one!=null){
                testSoulVo.setReportId(one.getId().toString());
            }
            //判断是否有初级report没有则将锁住
            if("初级".equals(soulTest.getLevel())){
                testSoulVo.setIsLock(0);
            }
            if("中级".equals(soulTest.getLevel())){
                Query queryMid =new Query(Criteria.where("userId").is(userId).and("level").is("初级"));
                boolean exists = mongoTemplate.exists(queryMid, SoulReport.class);
                if(exists){
                    testSoulVo.setIsLock(0);
                }
            }
            if("高级".equals(soulTest.getLevel())){
                Query queryMid =new Query(Criteria.where("userId").is(userId).and("level").is("中级"));
                boolean exists = mongoTemplate.exists(queryMid, SoulReport.class);
                if(exists){
                    testSoulVo.setIsLock(0);
                }
            }
          /*  if("特级".equals(soulTest.getLevel())){
                Query queryMid =new Query(Criteria.where("userId").is(userId).and("level").is("高级"));
                boolean exists = mongoTemplate.exists(queryMid, SoulReport.class);
                if(exists){
                    testSoulVo.setIsLock(0);
                }
            }*/
            listSoulTest.add(testSoulVo);
        }
        return listSoulTest;
    }

    @Override
    public String saveSoulList(List<SoulAnswer> answers,long userId) {
        //遍历查询得到总分
        int score=0;
        //获取哪份题目
        SoulAnswer soulAnswer = answers.get(0);
        System.out.println("通过第一个题目获取哪份题目"+soulAnswer);
        String questionId = soulAnswer.getQuestionId();
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("id",questionId);
        SoulQuestion soulQuestion = questionMapper.selectOne(wrapper);
        Integer sid = soulQuestion.getSid();
        //获取哪份级别
        SoulTest soulTest = soulTestMapper.selectById(sid);
        for (SoulAnswer answer : answers) {
           QueryWrapper queryWrapper=new QueryWrapper();
           queryWrapper.eq("id",answer.getOptionId());
            QuestionOption questionOption = questionOptionMapper.selectOne(queryWrapper);
            Integer score1 = questionOption.getScore();
            score=score+score1;
        }
        System.out.println("socre===》得分"+score);
        //通过总得分判断属于什么性格
        QueryWrapper clusion=new QueryWrapper();
        clusion.eq("sid",sid);
        clusion.le("startscore",score);
        clusion.ge("endscore",score);
        SoulConclusion soulConclusion = conclusionMapper.selectOne(clusion);
        //判断是否有同个级别的报告,没有则创建，有则更新
        String level = soulTest.getLevel();
        Query query=new Query(Criteria.where("level").is(level).and("userId").is(userId));
        SoulReport soulReport = mongoTemplate.findOne(query, SoulReport.class);
        long time = new Date().getTime();
        if(soulReport==null){
            //存储report
            soulReport=new SoulReport();
            soulReport.setUserId(userId);
            soulReport.setLevel(soulTest.getLevel());
            soulReport.setCreated(time);
            soulReport.setUpdated(time);
            mongoTemplate.save(soulReport);
        }
        Update update=new Update();
        update.set("conclusionId",soulConclusion.getId());
        update.set("conclusion",soulConclusion.getConclusion());
        update.set("cover",soulConclusion.getCover());
        update.set("dimensions",soulConclusion.getDimensions());
        update.set("score",score);
        update.set("updated",time);
        mongoTemplate.updateFirst(query,update,SoulReport.class);
        //返回id
        return soulReport.getId().toString();
    }

    @Override
    public ReportVo getReport(String id) {
        //查询report
        Query query = new Query(Criteria.where("id").is(new ObjectId(id)));
        SoulReport one = mongoTemplate.findOne(query, SoulReport.class);
        //通过性格id,查询类似的人员
        List<DimensionsVo> dimensionsVoList = new ArrayList<>();
        List<SimilarYouVo> similarYouList = new ArrayList<>();
        Integer conclusionId = one.getConclusionId();
        Query queryByconclusId = new Query(Criteria.where("conclusionId").is(Integer.parseInt(conclusionId.toString())));
        List<SoulReport> soulReports = mongoTemplate.find(queryByconclusId, SoulReport.class);
        System.out.println("报告==================>"+soulReports);
        //如果相似人的report不为空,遍历获取人员id然后获取信息封装,随机获取并且小于10个
        if(soulReports!=null) {
            Random random = new Random();
            Set<Integer> set = new HashSet<>();
            set.add(one.getUserId().intValue());
            o:while (similarYouList.size() < 10&&(soulReports.size()-1)>similarYouList.size()) {
                int i = random.nextInt(soulReports.size());
                if (!set.contains(soulReports.get(i).getUserId())) {
                    Long userId = soulReports.get(i).getUserId();
                //    if(userId!=one.getUserId()) {
                        UserInfo userInfo = userInfoMapper.selectById(userId);
                        String avatar = userInfo.getAvatar();
                        SimilarYouVo similarYouVo = new SimilarYouVo(userId.intValue(), avatar);
                        similarYouList.add(similarYouVo);
                        set.add(i);
                   // }
                }
            }
        }
        //封装dimensions,分割","再分割"",添加到集合
        String dimensions = one.getDimensions();
        String[] singleDimension = dimensions.split(",");
        for (String s : singleDimension) {
            String[] split = s.split("-");
            DimensionsVo dimensionsVo=new DimensionsVo(split[0],split[1]);
            dimensionsVoList.add(dimensionsVo);
        }
        //封装reportVo并返回
        ReportVo reportVo=new ReportVo();
        reportVo.setDimensions(dimensionsVoList);
        reportVo.setSimilarYou(similarYouList);
        reportVo.setConclusion(one.getConclusion());
        reportVo.setCover(one.getCover());
        return reportVo;
    }
    @Override
    public void insert(SoulTest soulTest) {
        soulTestMapper.insert(soulTest);
    }

    @Override
    public SoulTest selectOne(String name) {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("name",name);
        SoulTest soulTest = soulTestMapper.selectOne(wrapper);
        return soulTest;
    }

    @Override
    public SoulTest selectById(int sid) {
        SoulTest soulTest = soulTestMapper.selectById(sid);
        return soulTest;
    }

    @Override
    public void updateById(SoulTest soulTest) {
        soulTestMapper.updateById(soulTest);
    }

    @Override
    public List<SoulTest> getSoulTest() {
        List<SoulTest> list = soulTestMapper.selectList(null);
        return list;
    }

    @Override
    public List<SoulQuestion> getSoulQuestion(int id) {
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("sid",id);
        List<SoulQuestion> list = questionMapper.selectList(wrapper);
        return list;
    }
    @Transactional
    @Override
    public void deleteById(String id) {
        //查询该主题下的option
        QueryWrapper wrapper=new QueryWrapper<>();
        wrapper.eq("sid",id);
        List<SoulQuestion> list = questionMapper.selectList(wrapper);
        for (SoulQuestion soulQuestion : list) {
            //根据questionid删除option
            Integer id1 = soulQuestion.getId();
            QueryWrapper wrapperoption=new QueryWrapper();
            wrapperoption.eq("qid",id1);
            questionOptionMapper.delete(wrapperoption);
        }
        //删除主题下的题目
        questionMapper.delete(wrapper);
        //删除主题
        soulTestMapper.deleteById(id);
        //删除测试结果
        QueryWrapper wrapperConclusion=new QueryWrapper();
        wrapperConclusion.eq("sid",id);
        conclusionMapper.delete(wrapperConclusion);
    }
    @Transactional
    @Override
    public void deleteByTwoId(String qid) {
        //删除指定的option
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("qid",qid);
        questionOptionMapper.delete(wrapper);
        //删除指定的question
        questionMapper.deleteById(qid);
    }

    @Override
    public void updateAdByid(String userId) {
        Query query=new Query(Criteria.where("userId").is(Integer.parseInt(userId)));
        Update update=new Update();
        update.set("ad",1);
        mongoTemplate.updateFirst(query,update,SoundTime.class);
    }

    @Override
    public SoundTime selectSoundTimeById(String userId) {
        Query query=new Query(Criteria.where("userId").is(Integer.parseInt(userId)));
        SoundTime one = mongoTemplate.findOne(query, SoundTime.class);
        return one;
    }

    @Override
    public void updatePayByid(String userId,int type) {
        Query query=new Query(Criteria.where("userId").is(Integer.parseInt(userId)));
        Update update=new Update();
        update.set("pay",type);
        //增加次数
        Query query1=new Query(Criteria.where("userId").is(Integer.parseInt(userId)));
        Update updateaddTime=new Update();;
        updateaddTime.inc("time",11);
        mongoTemplate.updateFirst(query1,updateaddTime,SoundTime.class);
        mongoTemplate.updateFirst(query,update,SoundTime.class);
    }
}
